<template>
  <div class="posts-tab">
    <Product
      :products="products"
      :loading="loading"
      :loadMoreLoading="loadMoreLoading"
      :hasMore="hasMore" />
  </div>
</template>

<script setup lang="ts">
  import Product from '@/views/home/components/product.vue';
  import { ref, onMounted, onUnmounted, watch, onActivated, onDeactivated, nextTick } from 'vue';
  import { FeedsAPI, type FeedItem, type FeedsParams } from '@/api/feeds';
  import request from '@/utils/request';
  import { throttle } from 'lodash';
  import { onBeforeRouteLeave } from 'vue-router';

  // 接收父组件传递的uid
  const props = defineProps<{
    uid: number | string;
  }>();

  // 分页相关数据
  const start = ref(0);
  const loading = ref(false);
  // 产品数据
  const products = ref<FeedItem[]>([]);

  // 触底加载相关
  const loadMoreLoading = ref(false);
  const hasMore = ref(true);

  const isFirstMount = ref(true);
  const isActivated = ref(false);
  const isReturningFromOtherPage = ref(false);
  const savedScrollPosition = ref(0);
  // 处理页面加载数据中就点击进入作品详情，瀑布流获取不到页面高度，在作品详情页返回图片堆叠到一起
  const isLeavePageLoadingMore = ref<boolean>(false);

  // 组件挂载时加载数据
  onMounted(() => {
    isActivated.value = true;
    loadProducts();
    window.addEventListener('scroll', throttleHandleScroll);
  });

  // 组件卸载时清理事件监听
  onUnmounted(() => {
    window.removeEventListener('scroll', throttleHandleScroll);
  });

  // 路由离开前保存滚动位置
  onBeforeRouteLeave((to: any, from: any, next: any) => {
    console.log('路由离开前保存滚动位置');
    // 数据加载更多时候就离开页面
    if (loadMoreLoading.value) {
      isLeavePageLoadingMore.value = true;
    }
    saveScrollPosition();
    next();
  });

  onActivated(() => {
    if (isFirstMount.value) {
      isFirstMount.value = false;
      console.log('首次挂载，跳过onActivated处理');
      return;
    }
    // 重新添加滚动监听
    window.addEventListener('scroll', throttleHandleScroll);

    // 延迟恢复滚动位置，确保DOM完全渲染
    const timer1 = setTimeout(() => {
      restoreScrollPosition();
      clearTimeout(timer1);
    }, 100); // 100ms延迟

    // 延迟激活滚动处理，避免立即触发
    const timer2 = setTimeout(() => {
      isActivated.value = true;
      clearTimeout(timer2);
    }, 500); // 500ms延迟

    // 延迟重置返回标志，允许正常滚动加载
    const timer3 = setTimeout(() => {
      isReturningFromOtherPage.value = false;
      clearTimeout(timer3);
      console.log('重置返回标志，允许正常滚动加载');
    }, 1000); // 1秒后允许正常滚动加载

    if (isLeavePageLoadingMore.value) {
      loadMore();
      console.log('加载更多情况');
    }
    isLeavePageLoadingMore.value = false;
  });

  onDeactivated(() => {
    // 标记为从其他页面返回
    isReturningFromOtherPage.value = true;
    // 移除滚动监听
    window.removeEventListener('scroll', throttleHandleScroll);
  });

  // 保存滚动位置
  const saveScrollPosition = () => {
    // 使用nextTick确保DOM更新完成后再保存
    nextTick(() => {
      savedScrollPosition.value = window.pageYOffset || document.documentElement.scrollTop;
    });
  };

  // 恢复滚动位置（无动画）
  const restoreScrollPosition = () => {
    if (savedScrollPosition.value > 0) {
      // 使用nextTick确保DOM渲染完成后再恢复
      nextTick(() => {
        // 使用scrollTo的behavior: 'instant'来避免滚动动画
        window.scrollTo({
          top: savedScrollPosition.value,
          left: 0,
          behavior: 'instant',
        });
      });
    }
  };

  // 获取产品数据
  const loadProducts = async (isLoadMore = false) => {
    try {
      if (isLoadMore) {
        loadMoreLoading.value = true;
      } else {
        loading.value = true;
      }

      const params: FeedsParams = {
        start: start.value,
        size: 30,
        uid: props.uid, // 使用父组件传递的uid
      };

      console.log('获取用户posts数据，参数:', params);

      const response = await FeedsAPI.getFeeds(params);

      // 处理页面加载数据中就点击进入作品详情，瀑布流获取不到页面高度，在作品详情页返回图片堆叠到一起
      if (isLeavePageLoadingMore.value) {
        loading.value = false;
        loadMoreLoading.value = false;
        return;
      }

      if (isLoadMore) {
        // 追加数据
        products.value = [...products.value, ...response.data.feeds];
      } else {
        // 替换数据
        products.value = response.data.feeds;
      }

      start.value = response.data.next_start;

      // 检查是否还有更多数据
      hasMore.value = response.data.has_more;

      console.log('加载用户posts数据成功:', response);
    } catch (error) {
      console.error('加载用户posts数据失败:', error);
    } finally {
      loading.value = false;
      loadMoreLoading.value = false;
    }
  };

  // 触底加载更多数据
  const loadMore = async () => {
    if (loadMoreLoading.value || !hasMore.value || loading.value) return;

    // 更新start值以获取下一页数据
    start.value = products.value.length;

    await loadProducts(true);
  };

  // 滚动监听函数（节流处理）
  const handleScroll = () => {
    // 如果组件刚激活，延迟处理滚动事件、从其他页面返回，禁用滚动加载、正在加载或没有更多数据，则不处理滚动
    if (
      !isActivated.value ||
      isReturningFromOtherPage.value ||
      loadMoreLoading.value ||
      !hasMore.value
    ) {
      return;
    }
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;

    // 当滚动到距离底部100px时触发加载
    if (scrollTop + windowHeight >= documentHeight - 100) {
      loadMore();
    }
  };

  const throttleHandleScroll: any = throttle(handleScroll, 300);
  watch(
    () => props.uid,
    (newVal: number | string) => {
      console.log(newVal, 'newVal ===');

      loadProducts();
    }
  );
</script>

<style scoped lang="scss">
  .posts-tab {
    .tab-header {
      margin-bottom: 24px;
    }

    .posts-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 16px;
    }

    .post-placeholder {
      background: #fff;
      border-radius: 8px;
      padding: 16px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
  }
</style>
